using UnityEngine;
using QFramework;
using UnityEngine.Video;
using System.Collections;
using System.Collections.Generic;
using System;
using Unity.VisualScripting;

namespace ProjectSurvivor
{

	public partial class EnemyGenerator : ViewController
	{
		[SerializeField]
		public LevelConfig Config;
		float mCurrentGenerateSeconds = 0;
		private float mCurrentWaveSeconds = 0;

		public static BindableProperty<int> EnemyCount = new BindableProperty<int>(0);

		private int mTotalCount = 0;
		public Queue<EnemyWave> mEnemyWaveQueue = new Queue<EnemyWave>();


		public int WaveCount = 0;

		public bool LastWave => WaveCount == mTotalCount;

		public EnemyWave CurrenWave => mCurrenWave;
		void Start()
		{
			foreach (var group in Config.EnemyWaveGroups)
			{
				foreach (var wave in group.Waves)
				{
					mEnemyWaveQueue.Enqueue(wave);
					mTotalCount++;
				}
			}
		}

		private EnemyWave mCurrenWave = null;
		void Update()
		{

			if (mCurrenWave == null)
			{
				if (mEnemyWaveQueue.Count > 0)
				{
					WaveCount++;
					mCurrenWave = mEnemyWaveQueue.Dequeue();
					mCurrentGenerateSeconds = 0;
					mCurrentWaveSeconds = 0;
				}
			}

			if (mCurrenWave != null)
			{
				mCurrentGenerateSeconds += Time.deltaTime;
				mCurrentWaveSeconds += Time.deltaTime;


				if (mCurrentGenerateSeconds >= mCurrenWave.GenerateDuration)
				{
					mCurrentGenerateSeconds = 0;
					Player player = Player.Default;
					if (player)
					{
						var xOry = RandomUtility.Choose(-1, 1);
						var pos = Vector2.zero;
						if (xOry == -1)
						{
							pos.x = RandomUtility.Choose(CameraConuolier.LBTrans.position.x,
							CameraConuolier.RTTrans.position.x);
							pos.y = UnityEngine.Random.Range(CameraConuolier.LBTrans.position.y,
							CameraConuolier.RTTrans.position.y);
						}
						else
						{
							pos.x = UnityEngine.Random.Range(CameraConuolier.LBTrans.position.x,
							CameraConuolier.RTTrans.position.x);
							pos.y = RandomUtility.Choose(CameraConuolier.LBTrans.position.y,
							CameraConuolier.RTTrans.position.y);
						}
						
						mCurrenWave.EnemyPrefab
						.Instantiate()
						.Position(pos)
						.Self(self =>
						{
							var enemy = self.GetComponent<IEnemy>();
							enemy.SetSpeedScale(mCurrenWave.SpeedScale);
							enemy.SetHPScalg(mCurrenWave.HpScale);
						})
						.Show();
					}
				}

				if (mCurrentWaveSeconds >= mCurrenWave.Seconds)
				{
					mCurrenWave = null;
				}

			}

		}
	}
}
